#include<stdio.h>
#include<string.h>
//#include <unistd.h>
//#include <sys/ioctl.h>
#include <fcntl.h>

#define MAX_SIZE 0x1000
static unsigned char src[MAX_SIZE], dest[MAX_SIZE];

#define GMEM_DEVICE "/dev/gmem"  /* 'sudo mknod /dev/gmem c 250 0' */

int main(int argc, char *argv[])
{
  int fd = -1; 
  int rt = 0;
  int i = 0;
  unsigned char *tmp;
  
  printf("This test APP is to test for globalmem driver\n");
  if(argc != 2)
  {
    printf("error para! usage: %s read|write|reset\n", argv[0]);
    return 1;
  }

  fd = open(GMEM_DEVICE, O_RDWR);
  if(fd<0)
  {
    printf("open device fail\n");
    return 2;
  }

  /***************/
  if(strcmp(argv[1], "read") == 0)
  {
    rt = read(fd, src, 16);
    if(rt < 0)
    {
      printf("read error\n");
      close(fd);
      return 3;
    }
    else
    {
      tmp = src;
      printf("read %d bytes successful:\n", rt);
      printf("0x0000: 0x%02x 0x%02x 0x%02x 0x%02x\n", *tmp, *(tmp+1), *(tmp+2), *(tmp+3));
      tmp += 4;
      printf("0x0000: 0x%02x 0x%02x 0x%02x 0x%02x\n", *tmp, *(tmp+1), *(tmp+2), *(tmp+3));
      tmp += 4;
      printf("0x0000: 0x%02x 0x%02x 0x%02x 0x%02x\n", *tmp, *(tmp+1), *(tmp+2), *(tmp+3));
      tmp += 4;
      printf("0x0000: 0x%02x 0x%02x 0x%02x 0x%02x\n", *tmp, *(tmp+1), *(tmp+2), *(tmp+3));
      tmp += 4;
    }
  }
  else if(strcmp(argv[1], "write") == 0)
  {
    /****************/
    for(i=0; i<16; i++)
    {
      dest[i] = i;
    }
    //lseek(fd, 0, 0);
    rt = write(fd, dest, 16);
    if(rt < 0)
    {
      printf("write error\n");
      close(fd);
      return 4;
    }
  }
  else if(strcmp(argv[1], "reset") == 0)
  {
    /****************/
    for(i=0; i<16; i++)
    {
      dest[i] = 0;
    }
    //lseek(fd, 0, 0);
    #if 0
    rt = write(fd, dest, 16);
    #else
    rt = ioctl(fd, 0x01);
    #endif
    if(rt < 0)
    {
      printf("reset error\n");
      close(fd);
      return 5;
    }
  }
  else
  {
    printf("operation not recognized\n");
    close(fd);
    return 6;
  }
  close(fd);
    
  return 0;
}
